# -*- coding: utf-8 -*-
# @Time    : 2020/10/22 17:21
# @Author  : Leo
# @FileName: send_email.py
# @Software: PyCharm

import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header
from email.mime.multipart import MIMEMultipart
from modules.user import wechat_request

import requests
from email.utils import formataddr

class WechatQREmail(object):
    WECHAT_EMAILE_SUBJECT = 'AnyHungry微信通知接收验证'

    def __init__(self):
        self.SMTP_PORT = None
        self.SMTP_SERVER = None
        self.FROM_ADD = None
        self.FROM_ADD_PWD = None
        self.__set_smtp_info()
    def __set_smtp_info(self):
        '''
        设置smtp信息
        @return:
        以163 邮箱配置为例
        host=“smpt.163.com”
        port=25 【不使用TLS】
        或
        port=465 【使用TLS】
        '''


        self.SMTP_PORT = 465
        self.SMTP_SERVER = "smtp.163.com"
        self.FROM_ADD =  "yangleduoli@163.com"
        self.FROM_ADD_PWD = "ACKLJWSJXCCGUGJR"
        # self.SMTP_PORT = 587
        # self.SMTP_SERVER = "10.10.1.5"
        # self.FROM_ADD =  "Linda.fu@aishu.cn"
        # self.FROM_ADD_PWD = "fuyaolin1016.."


    def __create_wechat_emial_content(self, QR_URL):
        wechat_email_content = """
                <p><h3>尊敬的AnyHungry用户:</h3></p>
                <p>\n您好！管理员为您开通了微信通知消息接收功能，可用于用餐通知接收。如同意接收，请用微信扫描以下二维码并关注\"AnyHungry订餐平台\"，即可接收相关消息。</p>
                <div style="width:430px;">
                <p align="center"><img src="cid:QR"></p>
                <p align="center">（二维码有效期为30分钟）</p>
                </div>
                <p style="margin-bottom:2px;">若图片无法正常显示，请复制链接至浏览器中打开:</p>
                <p style="margin-top:2px;"><a href=%s>%s</a></p>
                <p style="margin-top:30px;">此致</p>
                <strong style="margin-top:5px;">AnyHungry团队</strong>
                """ % (QR_URL, QR_URL)
        return wechat_email_content


    def sendMail(self, to_addr, userId):
        '''

        @param from_addr: 发送方邮件账号
        @param from_addr_password: 发送方邮件账号密码
        @param to_addr: 接收方邮箱
        @param userId: 用于获取携带userId的关注微信二维码
        @return:
        '''
        '''
        发送微信绑定邮件
        '''
        QR_URL = wechat_request.WechatRequest.getQR(userId)  # 获取携带用户id的微信订阅二维码
        content = self.__create_wechat_emial_content(QR_URL)     # 邮件内容
        subject = self.WECHAT_EMAILE_SUBJECT # 邮件主题
        # print(content)

        port = self.SMTP_PORT # SMTP端口


        msg = MIMEMultipart('related')

        if self.FROM_ADD.split('@')[-1] ==  to_addr.split('@')[-1]:
            # 邮件头信息
            msg['From'] = Header('AnyHungry订餐平台 <%s>'%self.FROM_ADD, "utf-8")
            msg['To'] = Header(to_addr,"utf-8")
            msg['Subject'] = Header(subject, "utf-8")
        else:
            msg['From'] = formataddr(('AnyHungry订餐平台', self.FROM_ADD))  # Header( email_from, 'utf-8')
            msg['To'] = formataddr((to_addr.split('@')[0], to_addr))  # Header(email_to, 'utf-8')
            msg['Subject'] = subject
        msgAlternative = MIMEMultipart('alternative')
        msg.attach(msgAlternative)


        msgAlternative.attach(MIMEText(content, 'html', 'utf-8'))
        # 先下载URL里的图片，放到邮件内容里
        res = requests.get(QR_URL, 'rb')
        with open('temp.png', 'wb') as f:
            f.write(res.content)
        fp = open('temp.png', 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()

        # 定义图片 ID，在 HTML 文本中引用
        msgImage.add_header('Content-ID', '<QR>')
        msg.attach(msgImage)

        server = smtplib.SMTP_SSL(host=self.SMTP_SERVER, port=self.SMTP_PORT)
        # server.starttls()
        server.login(self.FROM_ADD, self.FROM_ADD_PWD)
        server.sendmail(self.FROM_ADD, to_addr, msg.as_string())
        server.close()

        return "微信绑定邮件发送成功"